const jwt = require('jsonwebtoken')

const {JWT_SECRET} = require('../config/config.default')

const {
	addBusiness,
	find,
	getApply,
	passBusiness,
	getAll,
	updateInfo,
	updateStatus,
	getBusinessInfo
} = require('../service/business.service')

const { businessErr,loginErr } = require('../constant/err.type')



class BusinessController {
	async register(ctx) {
		const { business_name, address, director, phone, password } = ctx.request.body
		const res = await find({ business_name, address })
		if (res) {
			ctx.app.emit('error', businessErr, ctx)
		}
		else {
			const res = await addBusiness({ business_name, address, director, phone, password })
			ctx.body = {
				code: 0,
				res
			}
		}
	}

	async login(ctx) {
		const { phone, pwd } = ctx.request.body
		if(phone == "admin" && pwd == "admin"){
			// let res = {}
			ctx.body = {
				code: 0,
				message: '超级管理员登录成功',
				result: {
					token: jwt.sign({},JWT_SECRET,{ expiresIn: '1d' })
				}
			}
		}
		else{
			try {
				const { password, ...res } = await getBusinessInfo({ phone, pwd })
				ctx.body = {
					code: 0,
					message: '登录成功',
					res,
					result: {
						token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
					}
				}
			} catch (error) {
				ctx.app.emit('error', loginErr, ctx)
			}
		}
		

		
	}

	async approve(ctx) {
		const res = await getApply()
		ctx.body = {
			res
		}
	}

	async pass(ctx) {
		const id = ctx.request.body.id
		const res = await passBusiness(id)
		ctx.body = {
			code: 0,
			message: "审核已通过",
			result: ""
		}
	}

	async findAllBusiness(ctx) {
		const res = await getAll()
		ctx.body = {
			res
		}
	}

	async update(ctx) {
		const { business_name, director, phone } = ctx.request.body
		const id = ctx.request.query.id
		const res = await updateInfo({ business_name, director, phone }, id)

		ctx.body = {
			code: 0,
			message: '修改成功'
		}
	}

	async remove(ctx) {
		const id = ctx.request.body.id
		await updateStatus(id)
		ctx.body = {
			code: 0,
			message: '删除成功'
		}
	}
}

module.exports = new BusinessController()